import { constantRouterMap, constantProviderRouterMap } from '@/router'
import { getUserInfo } from '../../utils/auth'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission (roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
}
const cutArray = function (data, cc) {
  let rt = []
  cc.forEach((el, index) => {
    if (data.indexOf(el.name) != -1) {
      rt.push(el)
      if (el.children && el.children.length) {
        el.children = cutArray(data, el.children)
      }
    }
  })
  return rt
}
const permission = {
  state: {
    routers: [],
    currentMenuIndex: 0,
    addRouters: [],
    permlist: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = routers// constantRouterMap.concat(routers);
    },
    SET_MENU_INDEX (state, idx) {
      state.currentMenuIndex = idx
    },
    SET_PERM_LIST (state, permlist) {
      state.permlist = permlist
    }
  },
  actions: {
    changeMenuIndex ({ commit }, idx) {
      commit('SET_MENU_INDEX', idx)
    },
    GenerateRoutes ({ commit }, data) {
      commit('SET_PERM_LIST', data)
      // let userInfo = getUserInfo()
      // if (userInfo && userInfo.userType == 1) { // 供应商权限
      //   commit('SET_ROUTERS', constantProviderRouterMap)
      //   commit('SET_MENU_INDEX', 0)
      // } else {
      let cc = [].concat(JSON.parse(JSON.stringify(constantRouterMap)))
      // let yy = cutArray(data, cc)
      // debugger;
      let yy = cc;
      commit('SET_ROUTERS', yy)
      commit('SET_MENU_INDEX', 0)
      // }

      // return new Promise(resolve => {
      //   const { roles } = data;
      //   let accessedRouters;
      //   if (roles.indexOf("admin") >= 0) {
      //     accessedRouters = asyncRouterMap;
      //   } else {
      //     accessedRouters = filterAsyncRouter(asyncRouterMap, roles);
      //   }
      //   commit("SET_ROUTERS", accessedRouters);
      //   resolve();
      // });
    }
  }
}

export default permission
